// // src/router/index.js
// import Vue from 'vue';
// import Router from 'vue-router';
// import store from '@/store'; // 直接 import Vuex Store

// Vue.use(Router);

// const router = new Router({
//   mode: 'history',
//   routes: [
//     {
//       path: '/',
//       redirect: '/home'
//     },
//     {
//       path: '/',
//       component: () => import(/* webpackChunkName: "home" */ '../components/common/Home.vue'),
//       meta: { title: '自述文件' },
//       children: [
//         {
//           path: '/home',
//           component: () => import('../view/Home.vue'),
//           meta: {
//             title: '系统首页',
//             roles: ['ROLE_TOLL_ADMIN', 'ROLE_TRAVEL_ADMIN', 'ROLE_SUPER_ADMIN',"ROLE_IMAGE_ADMIN","ROLE_LODGING_ADMIN"]
//           }
//         },
//         {
//           path: '/user',
//           component: () => import(/* webpackChunkName: "table" */ '../view/User.vue'),
//           meta: {
//             title: '用户管理',
//             roles: ['ROLE_TOLL_ADMIN', 'ROLE_TRAVEL_ADMIN', 'ROLE_SUPER_ADMIN']
//           }
//         },
//         {
//           path: '/loding',
//           component: () => import(/* webpackChunkName: "table" */ '../view/Lodging.vue'),
//           meta: {
//             title: '住宿管理',
//             roles: [ 'ROLE_TRAVEL_ADMIN', 'ROLE_SUPER_ADMIN',"ROLE_LODGING_ADMIN"]
//           }
//         },
//         {
//           path: '/hotel',
//           component: () => import(/* webpackChunkName: "table" */ '../view/Hotel.vue'),
//           meta: {
//             title: '酒店管理',
//             roles: ['ROLE_TRAVEL_ADMIN', 'ROLE_SUPER_ADMIN',"ROLE_LODGING_ADMIN"]
//           }
//         },
//         {
//           path: '/vehicle',
//           component: () => import(/* webpackChunkName: "table" */ '../view/Vehicle.vue'),
//           meta: {
//             title: '车辆管理',
//             roles: ['ROLE_TRAVEL_ADMIN', 'ROLE_SUPER_ADMIN']
//           }
//         },
//         {
//           path: '/vehicleAssignment',
//           component: () => import(/* webpackChunkName: "table" */ '../view/VehicleAssignment.vue'),
//           meta: {
//             title: '车辆分配管理',
//             roles: [ 'ROLE_TRAVEL_ADMIN', 'ROLE_SUPER_ADMIN']
//           }
//         },
//         {
//           path: '/conferences',
//           component: () => import(/* webpackChunkName: "table" */ '../view/Conferences.vue'),
//           meta: {
//             title: '会议管理',
//             roles: ['ROLE_TRAVEL_ADMIN', 'ROLE_SUPER_ADMIN']
//           }
//         },
//         {
//           path: '/participantType',
//           component: () => import(/* webpackChunkName: "table" */ '../view/ParticipantType.vue'),
//           meta: {
//             title: '用户类型管理',
//             roles: [ 'ROLE_SUPER_ADMIN']
//           }
//         },        
//         {
//           path: '/conferenceTypeFees',
//           component: () => import(/* webpackChunkName: "table" */ '../view/ConferenceTypeFees.vue'),
//           meta: {
//             title: '用户类型收费管理',
//             roles: [ 'ROLE_SUPER_ADMIN']
//           }
//         },
//         {
//           path: '/order',
//           component: () => import(/* webpackChunkName: "table" */ '../view/Order.vue'),
//           meta: {
//             title: '订单管理',
//             roles: ['ROLE_TOLL_ADMIN', 'ROLE_SUPER_ADMIN']
//           }
//         },
//         {
//           path: '/notification',
//           component: () => import(/* webpackChunkName: "table" */ '../view/Notifications.vue'),
//           meta: {
//             title: '通知管理',
//             roles: [ 'ROLE_SUPER_ADMIN']
//           }
//         },
//         {
//           path: '/images',
//           component: () => import(/* webpackChunkName: "table" */ '../view/Images.vue'),
//           meta: {
//             title: '图片上传管理',
//             roles: ['ROLE_SUPER_ADMIN',"ROLE_IMAGE_ADMIN"]
//           }
//         },
//         {
//           path: '/admin',
//           component: () => import(/* webpackChunkName: "table" */ '../view/Admin.vue'),
//           meta: {
//             title: '管理员管理',
//             roles: ['ROLE_SUPER_ADMIN']
//           }
//         },
//         {
//           path: '/map',
//           component: () => import(/* webpackChunkName: "table" */ '../view/Map.vue'),
//           meta: {
//             title: '景点管理',
//             roles: ['ROLE_SUPER_ADMIN']
//           }
//         }
//       ]
//     },
//     {
//       path: '/login',
//       component: () => import(/* webpackChunkName: "login" */ '../view/Login.vue'),
//       meta: { title: '登录' }
//     },
//     {
//       path: '/403',
//       component: () => import(/* webpackChunkName: "403" */ '../components/page/403.vue'),
//       meta: { title: '403' }
//     },
//     {
//       path: '/404',
//       component: () => import(/* webpackChunkName: "404" */ '../components/page/404.vue'),
//       meta: { title: '404' }
//     },
//     {
//       path: '*',
//       redirect: '/404'
//     }
//   ]
// });

// router.beforeEach(async (to, from, next) => {
//   // 1. 动态设置标题
//   document.title = `会议管理系统｜${to.meta.title || '未命名页面'}`;

//   // 2. 白名单：/login、/403、/404 直接放行
//   const whiteList = ['/login', '/403', '/404','/401'];
//   if (whiteList.includes(to.path)) {
//     return next();
//   }

//   // 3. 判断 Vuex.state.user 是否存在；如果是 null，说明前端还没拉过 currentUser
//   if (!store.state.user) {
//     try {
//       // 第一次进入，拉取后端当前用户
//       await store.dispatch('fetchCurrentUser');
//     } catch (err) {
//       // 3.1 如果抛错（401），说明没登录或 Session 失效，直接跳登录
//       return next({ path: '/login' });
//     }
//   }

//   // 4. 此时 store.state.user 已有值或已经在上一步抛过
//   const role = store.getters.userRole; // 从 Vuex 里取 role

//   // 5. 如果是超级管理员，直接放行
//   if (store.getters.isSuperAdmin) {
//     return next();
//   }

//   // 6. 只有普通管理员或收费管理员到这里，判断路由 meta.roles
//   const rolesAllowed = to.meta.roles; 
//   if (Array.isArray(rolesAllowed) && rolesAllowed.includes(role)) {
//     return next();
//   }

//   // 7. 走到这里，说明“普通或收费管理员”没权限，跳 403
//   return next({ path: '/403' });
// });

// export default router;

import Vue from 'vue';
import Router from 'vue-router';
import store from '@/store';

Vue.use(Router);

const routes = [
  {
    path: '/',
    component: () => import(/* webpackChunkName: "home" */ '../components/common/Home.vue'),
    meta: { title: '自述文件' },
    redirect: to => {
      // Ensure current user is loaded
      const user = store.state.user;
      if (!user) {
        // If not loaded, fetch then redirect
        return store.dispatch('fetchCurrentUser')
          .then(() => getRedirectPath())
          .catch(() => '/login');
      }
      return getRedirectPath();

      function getRedirectPath() {
        const role = store.getters.userRole;
        // Super admin always goes to /home
        if (role === 'ROLE_SUPER_ADMIN') {
          return '/home';
        }
        // Find first accessible child route (excluding /home)
        const child = routes[0].children.find(r => {
          const hasMeta = r.meta && Array.isArray(r.meta.roles);
          return r.path !== '/home' && hasMeta && r.meta.roles.includes(role);
        });
        return child ? child.path : '/403';
      }
    },
    children: [
      { path: '/home', component: () => import('../view/Home.vue'), meta: { title: '系统首页', roles: ['ROLE_SUPER_ADMIN'] } },
      { path: '/user', component: () => import('../view/User.vue'), meta: { title: '参会人员管理', roles: ['ROLE_TOLL_ADMIN','ROLE_SUPER_ADMIN','ROLE_LODGING_ADMIN','ROLE_TRAVEL_ADMIN'] } },
      { path: '/loding', component: () => import('../view/Lodging.vue'), meta: { title: '住宿管理', roles: ['ROLE_SUPER_ADMIN','ROLE_LODGING_ADMIN'] } },
      { path: '/hotel', component: () => import('../view/Hotel.vue'), meta: { title: '酒店管理', roles: ['ROLE_SUPER_ADMIN','ROLE_LODGING_ADMIN'] } },
      { path: '/vehicle', component: () => import('../view/Vehicle.vue'), meta: { title: '车辆管理', roles: ['ROLE_TRAVEL_ADMIN','ROLE_SUPER_ADMIN'] } },
      { path: '/vehicleAssignment', component: () => import('../view/VehicleAssignment.vue'), meta: { title: '车辆分配管理', roles: ['ROLE_TRAVEL_ADMIN','ROLE_SUPER_ADMIN'] } },
      { path: '/conferences', component: () => import('../view/Conferences.vue'), meta: { title: '会议管理', roles: ['ROLE_SUPER_ADMIN'] } },
      { path: '/participantType', component: () => import('../view/ParticipantType.vue'), meta: { title: '用户类型管理', roles: ['ROLE_SUPER_ADMIN'] } },
      { path: '/conferenceTypeFees', component: () => import('../view/ConferenceTypeFees.vue'), meta: { title: '用户类型收费管理', roles: ['ROLE_SUPER_ADMIN'] } },
      { path: '/order', component: () => import('../view/Order.vue'), meta: { title: '订单管理', roles: ['ROLE_TOLL_ADMIN','ROLE_SUPER_ADMIN'] } },
      { path: '/notification', component: () => import('../view/Notifications.vue'), meta: { title: '通知管理', roles: ['ROLE_SUPER_ADMIN'] } },
      { path: '/images', component: () => import('../view/Images.vue'), meta: { title: '图片上传管理', roles: ['ROLE_SUPER_ADMIN','ROLE_IMAGE_ADMIN'] } },
      { path: '/admin', component: () => import('../view/Admin.vue'), meta: { title: '管理员管理', roles: ['ROLE_SUPER_ADMIN'] } },
      { path: '/map', component: () => import('../view/Map.vue'), meta: { title: '景点管理', roles: ['ROLE_SUPER_ADMIN'] } },
      { path: '/liveSessions', component: () => import('../view/LiveSessions.vue'), meta: { title: '直播管理', roles: ['ROLE_SUPER_ADMIN'] } }
    ]
  },
  { path: '/login', component: () => import('../view/Login.vue'), meta: { title: '登录' } },
  { path: '/403', component: () => import('../components/page/403.vue'), meta: { title: '403' } },
  { path: '/404', component: () => import('../components/page/404.vue'), meta: { title: '404' } },
  { path: '*', redirect: '/404' }
];

const router = new Router({ mode: 'history', routes });

// Global guard
router.beforeEach(async (to, from, next) => {
  document.title = `会议管理系统｜${to.meta.title || '未命名页面'}`;

  const whiteList = ['/login','/403','/404','/401'];
  if (whiteList.includes(to.path)) return next();

  if (!store.state.user) {
    try {
      await store.dispatch('fetchCurrentUser');
    } catch (err) {
      return next('/login');
    }
  }

  // Super admin bypass
  if (store.getters.userRole === 'ROLE_SUPER_ADMIN') {
    return next();
  }

  const rolesAllowed = to.meta.roles;
  if (Array.isArray(rolesAllowed) && rolesAllowed.includes(store.getters.userRole)) {
    return next();
  }

  return next('/403');
});

export default router;
